package com.pphh.demo.amqp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Please add description here.
 *
 * @author huangyinhuang
 * @date 2019/3/27
 */
@Service
public class MqService {

    private final static Logger log = LoggerFactory.getLogger(MqService.class);

    @Autowired
    private AmqpTemplate amqpTemplate;

    public Boolean sendMessage(String msg) {
        log.info("try to send a message to rabbit mq, msg = {}", msg);
        amqpTemplate.convertAndSend("demo.queues.test.listen", msg);
        return Boolean.TRUE;
    }

    public Boolean sendDelayedMessage(String msg, Integer delayedMilliSeconds) {
        log.info("try to send a delayed message to rabbit mq, msg = {}", msg);

        amqpTemplate.convertAndSend("demo.queues.test.listen", (Object) msg, new MessagePostProcessor() {

            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setDelay(delayedMilliSeconds);
                return message;
            }

        });

        return Boolean.TRUE;
    }

    public Boolean sendMessageForPull(String msg) {
        log.info("try to send a message to rabbit mq (which will be pulled later), msg = {}", msg);
        amqpTemplate.convertAndSend("demo.queues.test.pull", msg);
        return Boolean.TRUE;
    }
}
